import axios, {
  type InternalAxiosRequestConfig,
  type AxiosResponse,
} from "axios";
import qs from "qs";
import { ResultEnum } from "@/enums/ResultEnum";
// import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
import router from "@/router"; // 导入路由实例
import { useAuthStore } from "@/store/auth";

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
  paramsSerializer: (params) => qs.stringify(params),
});

const WhiteList = [
  "/receptionLogin",
  "/homepage/courseList",
  "/homepage/newsList",
  "/homepage/teacherList",
  "/news/receptionSelectNewsList",
  "/news/selectNewsById",
  "/news/selectNewsById",
  "/news/selectNewsById",
  "/register",
  "/resetUserPwd",
  "/system/dict/data/type/subject",
  "/course/getCourseList",
  "/system/dict/data/type/course_type",
  "/course/getCourceChapterDetails/",
  "/getUserValue",
  "/teachers/",
];

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const authStore = useAuthStore();
    console.log(config.url);
    if (
      !WhiteList.some((path) => config.url?.includes(path)) &&
      !authStore.isAuthenticated
    ) {
      // 取消当前请求
      // return Promise.reject(new axios.Cancel("未认证，跳转到登录页"));

      // 或者直接重定向（注意：在拦截器中直接跳转可能会有些问题）
      router.push("/login");
      return Promise.reject("请登录后查看");
    }

    if (authStore.token) {
      config.headers.Authorization = `${authStore.token}`;
    }

    // const accessToken = getToken();
    // // 如果 Authorization 设置为 no-auth，则不携带 Token，用于登录、刷新 Token 等接口
    // if (config.headers.Authorization !== "no-auth" && accessToken) {
    //   config.headers.Authorization = `${accessToken}`;
    // } else {
    //   delete config.headers.Authorization;
    // }

    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 如果响应是二进制流，则直接返回，用于下载文件、Excel 导出等
    if (response.config.responseType === "blob") {
      return response;
    }

    const { code, data, msg } = response.data;

    if (code + "" === ResultEnum.SUCCESS) {
      return response.data;
    }

    if (code == "401") {
      // sessionStorage.clear();
      // router.push("/login");
      // return false;
      const authStore = useAuthStore();
      authStore.logout();
    }

    ElMessage.error(msg || "系统出错");
    return Promise.reject(new Error(msg || "Error"));
  },
  async (error) => {
    console.error("request error", error); // for debug
    // 非 2xx 状态码处理 401、403、500 等
    const { response } = error;
    console.log(response);

    if (response) {
      if (response.status === 401) {
        const authStore = useAuthStore();
        authStore.logout();
      }

      if (response.data.code == "203") {
        router.push("/401");
        return false;
      }
      const { code, msg } = response.data;
      if (code === ResultEnum.REFRESH_TOKEN_INVALID) {
        return Promise.reject(new Error(msg || "Error"));
      } else {
        ElMessage.error(msg || "系统出错");
      }
    }
    return Promise.reject(error.message);
  }
);

export default service;
